package com.wxzz.elearing.evaluation.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.lang.copier.Copier;
import cn.hutool.db.sql.Direction;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.evaluation.dto.*;
import com.wxzz.elearing.evaluation.entity.*;
import com.wxzz.elearing.evaluation.mapper.*;
import com.wxzz.elearing.evaluation.service.ITopicService;
import com.wxzz.elearing.evaluation.service.openfeign.IEnterpriseApiFeign;
import com.wxzz.elearing.evaluation.service.openfeign.IObsApiFeign;
import com.wxzz.elearing.evaluation.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearing.evaluation.vo.BusinessCategoryTopicIsPassVo;
import com.wxzz.elearing.evaluation.vo.ExportTopicAnswerVo;
import com.wxzz.elearing.evaluation.vo.ExportTopicVo;
import com.wxzz.elearing.evaluation.vo.TopicVo;
import com.wxzz.elearning.common.aop.Idempotent;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.dto.FeignDrawImageDto;
import com.wxzz.elearning.common.dto.FeignEnterpriseDto;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.ExcelTopicUtils;
import com.wxzz.elearning.common.utils.ExcelUtils;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import io.swagger.annotations.ApiModel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.IntFunction;

/**
 * <p>
 * 测评题库 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-10
 */
@Slf4j
@Service
public class TopicServiceImpl extends ServiceImpl<TopicMapper, Topic> implements ITopicService {

    @Autowired
    private TopicCategoryMapper topicCategoryMapper;

    @Autowired
    private TopicMapper topicMapper;

    @Idempotent
    @Override
    public ReturnVO saveTopicCategory(TopicCategory topicCategory) {
        if (topicCategory.getId() == null) {
            if (topicCategory.getPid() == null) {
                throw new ServiceException("请传入pid，顶级为0");
            }
            //设置层级
            if (topicCategory.getPid() == 0) {
                topicCategory.setLevel(1);
            } else {
                TopicCategory parent = topicCategoryMapper.selectById(topicCategory.getPid());
                if (parent == null) {
                    throw new ServiceException("pid对应层级不存在");
                } else {
                    Integer thisLevel = parent.getLevel() + 1;
                    if (thisLevel > 4) {
                        throw new ServiceException("层级不能超过4层");
                    }
                    topicCategory.setLevel(thisLevel);
                }
            }
            topicCategoryMapper.insert(topicCategory);
        } else {
            topicCategoryMapper.updateById(topicCategory);
        }
        return new ReturnVO("题目分类新增成功", topicCategory.getId());
    }

    @Override
    public ReturnVO deleteTopicCategory(Long topicCategoryId) {
        Integer count = topicMapper.selectCount(new LambdaQueryWrapper<Topic>()
                .eq(Topic::getTopicCategoryId, topicCategoryId));
        if (count > 0) {
            throw new ServiceException("该分类下还有题目");
        }
        topicCategoryMapper.deleteById(topicCategoryId);
        return new ReturnVO("题目分类删除成功", topicCategoryId);
    }

    @Override
    public ReturnVO<List<TopicCategory>> listTopicCategoryByPid() {
        List<TopicCategory> firsts = topicCategoryMapper.selectList(new LambdaQueryWrapper<TopicCategory>().eq(TopicCategory::getPid, 0));
        for (TopicCategory first : firsts) {
            List<TopicCategory> seconds = topicCategoryMapper.selectList(new LambdaQueryWrapper<TopicCategory>().eq(TopicCategory::getPid, first.getId()));
            first.setChildren(seconds);
            for (TopicCategory second : seconds) {
                List<TopicCategory> thirds = topicCategoryMapper.selectList(new LambdaQueryWrapper<TopicCategory>().eq(TopicCategory::getPid, second.getId()));
                second.setChildren(thirds);
                for (TopicCategory third : thirds) {
                    List<TopicCategory> fourths = topicCategoryMapper.selectList(new LambdaQueryWrapper<TopicCategory>().eq(TopicCategory::getPid, third.getId()));
                    third.setChildren(fourths);
                }
            }
        }
        return new ReturnVO("题目分类新增成功", firsts);
    }

    @Override
    public ReturnVO<Long> selectPid(Long id) {
        TopicCategory topicCategory = topicCategoryMapper.selectById(id);
        if (topicCategory != null) {
            return new ReturnVO("查询父级成功", topicCategory.getPid());
        }
        return new ReturnVO("查询父级成功", 0);
    }

    @Autowired
    private TopicAnswerMapper topicAnswerMapper;

    @Transactional
    @Override
    public ReturnVO saveTopic(Topic topic) {
//        if (topic.getBusinessCategoryId() == null) {
//            throw new ServiceException("请传入组别管理");
//        }
        if (topic.getTopicAnswerList() == null) {
            throw new ServiceException("请传入题目答案选项");
        }
        if (topic.getId() == null) {
            topicMapper.insert(topic);
        } else {
            topicMapper.updateById(topic);
            topicAnswerMapper.delete(new LambdaQueryWrapper<TopicAnswer>().eq(TopicAnswer::getTopicId, topic.getId()));
        }
//        List<TopicAnswer> topicAnswers = topicAnswerMapper.selectList(new LambdaQueryWrapper<TopicAnswer>().eq(TopicAnswer::getTopicId, topic.getId()));
//        topicAnswers.forEach(topicAnswer -> topicAnswerMapper.deleteByTopicAnswerId(topicAnswer.getId()));
        for (TopicAnswer topicAnswer : topic.getTopicAnswerList()) {
            topicAnswer.setId(null);
            topicAnswer.setTopicId(topic.getId());
            topicAnswerMapper.insert(topicAnswer);
        }
        return new ReturnVO("题目新增成功", topic.getId());
    }

    @Transactional
    @Override
    public ReturnVO deleteTopicById(Long id) {
        topicMapper.deleteById(id);
        //删除题目与组别的绑定关系
        businessCategoryTopicMapper.delete(new LambdaQueryWrapper<BusinessCategoryTopic>().eq(BusinessCategoryTopic::getTopicId,id));
        return new ReturnVO("题目删除成功", id);
    }

    @Autowired
    private BusinessCategoryTopicMapper businessCategoryTopicMapper;

    @Override
    public ReturnVO deleteBusinessCategoryTopic(Long businessCategoryTopicId) {
        businessCategoryTopicMapper.deleteById(businessCategoryTopicId);
        return new ReturnVO("删除工厂体检/星级认证/能力测评关联题目", businessCategoryTopicId);
    }

    @Override
    public ReturnVO updateTopicAnswer(TopicAnswer topicAnswer) {
        topicAnswerMapper.updateById(topicAnswer);
        return new ReturnVO("题目新增成功", topicAnswer.getId());
    }


    @Override
    public ReturnVO<JgPageVo<List<Topic>>> listTopic(TopicDto topicDto) {
        PageHelper.startPage(topicDto.getCurPage(), topicDto.getMaxPage());
        QueryWrapper<Topic> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        if (topicDto.getTopicCategoryIds() != null && topicDto.getTopicCategoryIds().size() != 0) {
            queryWrapper.in("topic_category_id", topicDto.getTopicCategoryIds());
        }
        if (StringUtils.isNotBlank(topicDto.getTopicName())) {
            queryWrapper.like("topic_name", topicDto.getTopicName() + "%");
        }
        List<Topic> topics = topicMapper.selectList(queryWrapper);
        for (Topic topic : topics) {
            //查询答案选项
            List<TopicAnswer> topicAnswers = topicAnswerMapper.selectList(new LambdaQueryWrapper<TopicAnswer>().eq(TopicAnswer::getTopicId, topic.getId()));
            topic.setTopicAnswerList(topicAnswers);
            topic.setTopicAnswerNum(topicAnswers.size());
            //题目使用数量
            Integer count = businessCategoryTopicMapper.selectCount(new LambdaQueryWrapper<BusinessCategoryTopic>()
                    .eq(BusinessCategoryTopic::getTopicId, topic));
            topic.setTopicUseNum(count);
        }
        return new ReturnVO("题库列表查询成功", new JgPageVo<>(new PageInfo(topics)));
    }

    @Autowired
    private BusinessCategoryMapper businessCategoryMapper;

    @Override
    public ReturnVO<JgPageVo<List<Topic>>> listInTopic(InTopicDto inTopicDto) {
        if (inTopicDto.getCommonId() == null) {
            throw new ServiceException("请传入commonId");
        }
        PageHelper.startPage(inTopicDto.getCurPage(), inTopicDto.getMaxPage());
        List<Topic> topics = topicMapper.listTopicJoinBusinessCategoryTopic(inTopicDto);
        for (Topic topic : topics) {
            //查询题目组别名称
            BusinessCategoryTopic businessCategoryTopic = businessCategoryTopicMapper.selectById(topic.getBusinessCategoryTopicId());
            if (businessCategoryTopic != null) {
                BusinessCategory businessCategory = businessCategoryMapper.selectById(businessCategoryTopic.getBusinessCategoryId());
                if (businessCategory != null) {
                    topic.setBusinessName(businessCategory.getBusinessName());
                }
            }
            //查询答案选项
            List<TopicAnswer> topicAnswers = topicAnswerMapper.selectList(new LambdaQueryWrapper<TopicAnswer>().eq(TopicAnswer::getTopicId, topic.getId()));
            topic.setTopicAnswerList(topicAnswers);
            //选项数量
            topic.setTopicAnswerNum(topicAnswers.size());
        }
        return new ReturnVO("详情题库查询成功", new JgPageVo<>(new PageInfo(topics)));
    }

    @Autowired
    private IWxUserApiFeign wxUserApiFeign;

    @Autowired
    private BusinessCategoryRuleMapper businessCategoryRuleMapper;

    @Autowired
    private WxUserBusinessCategoryGroupMapper wxUserBusinessCategoryGroupMapper;

    @Override
    public ReturnVO<TopicVo> wxListTopic(Integer type, Long wxUserId) {
        ReturnVO<String> stringReturnVO = wxUserApiFeign.selectEnterpriseByWxUserId(wxUserId);
        TopicVo topicVo = new TopicVo();
        if ("200".equals(stringReturnVO.getCode())) {
            JSONObject jsonObject = JSONObject.parseObject(stringReturnVO.getData());
            //取出企业的行业类目id
            Long businessCategoryId = jsonObject.getLong("businessCategoryId");
            //查询体检/星级的外侧数据
            BusinessCategoryRule businessCategoryRule = businessCategoryRuleMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRule>().eq(BusinessCategoryRule::getBusinessCategoryId, businessCategoryId)
                    .eq(BusinessCategoryRule::getType, type)
                    .orderByAsc(BusinessCategoryRule::getCreateTime));
            if (businessCategoryRule == null) {
                return new ReturnVO<>("试题查询成功", topicVo);
            }
            //查询是否有草稿
            Query query = new Query();
            query.addCriteria(Criteria.where("wxUserId").is(wxUserId))
                    .addCriteria(Criteria.where("type").is(0))
                    .addCriteria(Criteria.where("commonId").is(businessCategoryRule.getId()));
            List<TopicMongoDto> topicMongoDtos = mongoTemplate.find(query, TopicMongoDto.class);
            if (topicMongoDtos.size() != 0) {
                return new ReturnVO("试题查询成功", topicMongoDtos.get(0));
            }
            //查询用户是否有权限
            WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup = wxUserBusinessCategoryGroupMapper.selectOne(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                    .eq(WxUserBusinessCategoryGroup::getEnterpriseId, jsonObject.getLong("id"))
                    .eq(WxUserBusinessCategoryGroup::getType, 1)
                    .eq(WxUserBusinessCategoryGroup::getWxUserId, wxUserId)
                    .eq(WxUserBusinessCategoryGroup::getCommonId, businessCategoryRule.getId())
                    .eq(WxUserBusinessCategoryGroup::getExamStatus, 0));
            Optional.ofNullable(wxUserBusinessCategoryGroup).orElseThrow(() -> new ServiceException("您没有工厂体检的权限"));
            //根据体检/星级id查询分组
            List<BusinessCategory> businessCategories = businessCategoryMapper.selectList(new LambdaQueryWrapper<BusinessCategory>()
                    .eq(BusinessCategory::getType, type).eq(BusinessCategory::getCommonId, businessCategoryRule.getId()).orderByAsc(BusinessCategory::getCreateTime));
            //根据分组查询对应的题目
            List<Topic> topicList = Lists.newArrayList();
            for (BusinessCategory businessCategory : businessCategories) {
                List<Topic> topics = businessCategoryTopicMapper.selectTopicJoinBusinessCategoryTopic(type, businessCategoryRule.getId(), businessCategory.getId());
                for (Topic topic : topics) {
                    List<TopicAnswer> topicAnswers = topicAnswerMapper.selectList(new LambdaQueryWrapper<TopicAnswer>().eq(TopicAnswer::getTopicId, topic.getId()));
                    topic.setTopicAnswerList(topicAnswers);
                    topic.setBusinessCategoryId(businessCategory.getId());
                }
                topicList.addAll(topics);
            }
            //工厂体检id
            topicVo.setBusinessCategoryRuleId(businessCategoryRule.getId());
            topicVo.setBusinessCategorys(businessCategories);
            topicVo.setTopicList(topicList);
        }
        return new ReturnVO<>("试题查询成功", topicVo);
    }

    @Override
    public ReturnVO<TopicVo> wxListTopic4evaluation(Long wxUserId, Integer type, Long businessCategoryEvaluationId) {
        //查询是否有草稿
        Query query = new Query();
        query.addCriteria(Criteria.where("wxUserId").is(wxUserId))
                .addCriteria(Criteria.where("type").is(type))
                .addCriteria(Criteria.where("commonId").is(businessCategoryEvaluationId));
        List<TopicMongoDto> topicMongoDtos = mongoTemplate.find(query, TopicMongoDto.class);
        if (topicMongoDtos.size() != 0) {
            return new ReturnVO("试题查询成功", topicMongoDtos.get(0));
        }
        TopicVo topicVo = new TopicVo();
        //根据能力测评id查询分组
        List<BusinessCategory> businessCategories = businessCategoryMapper.selectList(new LambdaQueryWrapper<BusinessCategory>()
                .eq(BusinessCategory::getType, type).eq(BusinessCategory::getCommonId, businessCategoryEvaluationId).orderByAsc(BusinessCategory::getCreateTime));
        //根据分组查询对应的题目
        List<Topic> topicList = Lists.newArrayList();
        for (BusinessCategory businessCategory : businessCategories) {
            List<Topic> topics = businessCategoryTopicMapper.selectTopicJoinBusinessCategoryTopic(type, businessCategoryEvaluationId, businessCategory.getId());
            for (Topic topic : topics) {
                List<TopicAnswer> topicAnswers = topicAnswerMapper.selectList(new LambdaQueryWrapper<TopicAnswer>().eq(TopicAnswer::getTopicId, topic.getId()));
                topic.setTopicAnswerList(topicAnswers);
                topic.setBusinessCategoryId(businessCategory.getId());
            }
            topicList.addAll(topics);
        }
        topicVo.setBusinessCategorys(businessCategories);
        topicVo.setTopicList(topicList);
        return new ReturnVO<>("能力测评试题查询成功", topicVo);
    }

    @Autowired
    public MongoTemplate mongoTemplate;

    @Override
    public ReturnVO saveTopicMongoDto(TopicMongoDto topicMongoDto) {
        if (topicMongoDto.getCommonId() == null) {
            throw new ServiceException("请传入commonId");
        }
        //查询是否有草稿 先删除
        Query query = new Query();
        query.addCriteria(Criteria.where("wxUserId").is(topicMongoDto.getWxUserId()))
                .addCriteria(Criteria.where("type").is(topicMongoDto.getType()))
                .addCriteria(Criteria.where("commonId").is(topicMongoDto.getCommonId()));
        mongoTemplate.remove(query, TopicMongoDto.class);
        //新增
        topicMongoDto.setCreateTime(LocalDateTime.now());
        TopicMongoDto insert = mongoTemplate.insert(topicMongoDto);
        return new ReturnVO<>("草稿保存成功", insert.getUid());
    }

    @Override
    public ReturnVO<List<TopicMongoDto>> listTopicMongoDto(Long wxUserId, TopicMongoSelDto topicMongoSelDto) {
        if (topicMongoSelDto.getCommonId() == null) {
            throw new ServiceException("请传入commonId");
        }
        if (topicMongoSelDto.getType() == null) {
            throw new ServiceException("请传入type");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("wxUserId").is(wxUserId))
                .addCriteria(Criteria.where("type").is(topicMongoSelDto.getType()))
                .addCriteria(Criteria.where("commonId").is(topicMongoSelDto.getCommonId()));
        List<TopicMongoDto> topicMongoDtos = mongoTemplate.find(query, TopicMongoDto.class);
        return new ReturnVO<>("草稿箱列表查询成功", topicMongoDtos);
    }

    @Override
    public ReturnVO<TopicMongoDto> selectTopicMongoDtoByUid(String uid) {
        TopicMongoDto byId = mongoTemplate.findById(uid, TopicMongoDto.class);
        return new ReturnVO<>("查询草稿箱详情成功", byId);
    }

    @Autowired
    private BusinessCategoryEvaluationHistoryMapper businessCategoryEvaluationHistoryMapper;

    @Autowired
    private BusinessCategoryRuleHistoryMapper businessCategoryRuleHistoryMapper;

    @Autowired
    private BusinessCategoryReportMapper businessCategoryReportMapper;

    @Autowired
    private IEnterpriseApiFeign enterpriseApiFeign;

    @Autowired
    private IObsApiFeign obsApiFeign;

    @Transactional
    @Override
    public ReturnVO businessCategoryTopicIsPass(JSONObject jsonObject, BusinessCategoryTopicIsPassDto businessCategoryTopicIsPassDto) {
        if (businessCategoryTopicIsPassDto.getCommonId() == null) {
            throw new ServiceException("请传入commonId");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("wxUserId").is(jsonObject.getLong("id")))
                .addCriteria(Criteria.where("type").is(businessCategoryTopicIsPassDto.getType()))
                .addCriteria(Criteria.where("commonId").is(businessCategoryTopicIsPassDto.getCommonId()));
        mongoTemplate.remove(query, TopicMongoDto.class);
        //工厂体检/星级认证
        BusinessCategoryRuleHistory businessCategoryRuleHistory = new BusinessCategoryRuleHistory();
        if (businessCategoryTopicIsPassDto.getType() == 0 || businessCategoryTopicIsPassDto.getType() == 1) {
            BusinessCategoryRule businessCategoryRule = businessCategoryRuleMapper.selectById(businessCategoryTopicIsPassDto.getCommonId());
            businessCategoryRuleHistory.setRuleName(businessCategoryRule.getRuleName());
            businessCategoryRuleHistory.setRuleDescribe(businessCategoryRule.getRuleDescribe());
            businessCategoryRuleHistoryMapper.insert(businessCategoryRuleHistory);
        }
        //能力测评
        BusinessCategoryEvaluationHistory businessCategoryEvaluationHistory = new BusinessCategoryEvaluationHistory();
        if (businessCategoryTopicIsPassDto.getType() == 2) {
            BusinessCategoryEvaluation businessCategoryEvaluation = businessCategoryEvaluationMapper.selectById(businessCategoryTopicIsPassDto.getCommonId());
            businessCategoryEvaluationHistory.setProjectName(businessCategoryEvaluation.getItemName());
            businessCategoryEvaluationHistory.setItemDescribe(businessCategoryEvaluation.getItemDescribe());
            businessCategoryEvaluationHistoryMapper.insert(businessCategoryEvaluationHistory);
        }
        Integer chooseNum = 0;
        //总分
        BigDecimal allScore = new BigDecimal("0.00");
        //总得分
        BigDecimal allGetScore = new BigDecimal("0.00");
        //计算分数
        if (businessCategoryTopicIsPassDto.getBusinessCategorys() != null) {
            //循环分组
            for (BusinessCategory businessCategory : businessCategoryTopicIsPassDto.getBusinessCategorys()) {
                //分组得分
                BigDecimal businessCategoryGetAllScore = new BigDecimal("0.00");
                //分组总分
                BigDecimal businessCategoryAllScore = new BigDecimal("0.00");
                //取出题目
                List<Topic> topicList = businessCategoryTopicIsPassDto.getTopicList();
                //循环题目 如果题目是该分组的就进行判断
                for (Topic topic : topicList) {
                    String choose = "";
                    //计算选择的数量
                    if (topic.getIsChoose() == 1) {
                        chooseNum = chooseNum + 1;
                    }
                    if (topic.getBusinessCategoryId() != null && topic.getBusinessCategoryId().equals(businessCategory.getId())) {
                        //本题得分
                        BigDecimal topicScore = new BigDecimal("0.00");
                        if (topic.getTopicAnswerList() != null) {
                            for (TopicAnswer topicAnswer : topic.getTopicAnswerList()) {
                                //取出选择的分数
                                if (Boolean.TRUE.equals(topicAnswer.getIsChoose())) {
                                    if (topicAnswer.getScore() != null) {
                                        //计算总得分
                                        allGetScore = allGetScore.add(topicAnswer.getScore());
                                        //计算分组得分
                                        businessCategoryGetAllScore = businessCategoryGetAllScore.add(topicAnswer.getScore());
                                        //本题得分
                                        topicScore = topicScore.add(topicAnswer.getScore());
                                    }
                                    choose = choose + topicAnswer.getItem() + ",";
                                }
                                //计算总分
                                allScore = allScore.add(topicAnswer.getScore());
                                //计算分组总分数
                                businessCategoryAllScore = businessCategoryAllScore.add(topicAnswer.getScore());
                            }
                        }
                        TopicHistory topicHistory = new TopicHistory();
                        BeanUtils.copyProperties(topic, topicHistory);
                        topicHistory.setId(null);
                        //本题总得分
                        topicHistory.setScore(topicScore);
                        topicHistory.setItems(choose);
                        //题目记录
                        topicHistory.setAnswers(JSONObject.toJSONString(topic.getTopicAnswerList()));
                        topicHistory.setWxUserId(jsonObject.getLong("id"));
                        topicHistory.setBusinessType(businessCategoryTopicIsPassDto.getType());
                        //工厂体检/星级认证
                        if (businessCategoryTopicIsPassDto.getType() == 0 || businessCategoryTopicIsPassDto.getType() == 1) {
                            topicHistory.setCommonId(businessCategoryRuleHistory.getId());
                        }
                        //能力测评
                        if (businessCategoryTopicIsPassDto.getType() == 2) {
                            topicHistory.setCommonId(businessCategoryEvaluationHistory.getId());
                        }
                        topicHistory.setBusinessCategoryName(businessCategory.getBusinessName());
                        topicHistoryMapper.insert(topicHistory);
                    }
                }
                //计算分组得分
                businessCategory.setBusinessCategoryAllScore(businessCategoryGetAllScore);
                //计算分组百分比
                if (new BigDecimal("0.00").equals(businessCategoryAllScore)) {
                    //如果分组总分为0直接给100%
                    businessCategory.setBusinessCategoryPercentum(new BigDecimal("100.00"));
                } else {
                    //得分/总分*100
                    BigDecimal divide = businessCategoryGetAllScore.divide(businessCategoryAllScore, 2, BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal("100.00"));
                    businessCategory.setBusinessCategoryPercentum(divide);
                }
            }
        }
        //根据用户id换取企业信息
        ReturnVO<String> stringReturnVO = wxUserApiFeign.selectEnterpriseByWxUserId(jsonObject.getLong("id"));
        JSONObject enterpriseJson = OpenFeignUtil.getJSONObject(stringReturnVO);
        //综合能力测评建议
        String suggest = "";
        //测评建议查询
        List<BusinessCategoryReport> businessCategoryReports = businessCategoryReportMapper.selectList(new LambdaQueryWrapper<BusinessCategoryReport>()
                .eq(BusinessCategoryReport::getCommonId, businessCategoryTopicIsPassDto.getCommonId())
                .eq(BusinessCategoryReport::getType, businessCategoryTopicIsPassDto.getType()));
        //判断总分是否在区间内 给出提示
        for (BusinessCategoryReport businessCategoryReport : businessCategoryReports) {
            //如果在区间范围内
            if ((businessCategoryReport.getAllScoreFloor().compareTo(allGetScore) == -1
                    || businessCategoryReport.getAllScoreFloor().compareTo(allGetScore) == 0)
                    && (allGetScore.compareTo(businessCategoryReport.getAllScoreUpper()) == -1
                    || businessCategoryReport.getAllScoreFloor().compareTo(allGetScore) == 0)) {
                suggest = businessCategoryReport.getSuggest();
            }
        }
        //工厂体检/星级认证
        if (businessCategoryTopicIsPassDto.getType() == 0 || businessCategoryTopicIsPassDto.getType() == 1) {
            businessCategoryRuleHistory.setSuggest(suggest);
            //分组json
            if (businessCategoryTopicIsPassDto.getBusinessCategorys() != null) {
                businessCategoryRuleHistory.setBusinessCategorysJson(JSONObject.toJSONString(businessCategoryTopicIsPassDto.getBusinessCategorys()));
            }
            //设置工厂体检/星级认证辅助信息
            businessCategoryRuleHistory.setWxUserId(jsonObject.getLong("id"));
            businessCategoryRuleHistory.setEnterpriseId(jsonObject.getLong("enterpriseId"));
            businessCategoryRuleHistory.setBusinessCategoryRuleId(businessCategoryTopicIsPassDto.getCommonId());
            businessCategoryRuleHistory.setEnterpriseOrganizationId(jsonObject.getLong("enterpriseOrganizationId"));
            businessCategoryRuleHistory.setWxUserRealName(jsonObject.getString("nickname"));
            businessCategoryRuleHistory.setBusinessCategoryId(enterpriseJson.getLong("businessCategoryId"));
            businessCategoryRuleHistory.setEnterpriseName(enterpriseJson.getString("enterpriseName"));
            businessCategoryRuleHistory.setIcon(jsonObject.getString("icon"));
            businessCategoryRuleHistory.setPhone(jsonObject.getString("phone"));
            businessCategoryRuleHistory.setType(businessCategoryTopicIsPassDto.getType());
            businessCategoryRuleHistory.setAllScore(allGetScore);
            businessCategoryRuleHistory.setAnswerNum(chooseNum);
            //查询星级评定规则
            BusinessCategoryRule businessCategoryRule = businessCategoryRuleMapper.selectById(businessCategoryTopicIsPassDto.getCommonId());
            if (businessCategoryRule != null) {
                //设置标题
                businessCategoryRuleHistory.setRuleName(businessCategoryRule.getRuleName());
                //一星
                if ((businessCategoryRule.getOneStarFloor().compareTo(allGetScore) == -1 || businessCategoryRule.getOneStarFloor().compareTo(allGetScore) == 0)
                        && (allGetScore.compareTo(businessCategoryRule.getOneStarUpper()) == -1 || allGetScore.compareTo(businessCategoryRule.getOneStarUpper()) == 0)) {
                    businessCategoryRuleHistory.setStartLevel(1);
                }
                //二星
                if ((businessCategoryRule.getTwoStarFloor().compareTo(allGetScore) == -1 || businessCategoryRule.getTwoStarFloor().compareTo(allGetScore) == 0)
                        && (allGetScore.compareTo(businessCategoryRule.getTwoStarUpper()) == -1 || allGetScore.compareTo(businessCategoryRule.getTwoStarUpper()) == 0)) {
                    businessCategoryRuleHistory.setStartLevel(2);
                }
                //三星
                if ((businessCategoryRule.getThreeStarFloor().compareTo(allGetScore) == -1 || businessCategoryRule.getThreeStarFloor().compareTo(allGetScore) == 0)
                        && (allGetScore.compareTo(businessCategoryRule.getThreeStarUpper()) == -1 || allGetScore.compareTo(businessCategoryRule.getThreeStarUpper()) == 0)) {
                    businessCategoryRuleHistory.setStartLevel(3);
                }
                //四星
                if ((businessCategoryRule.getFourStarFloor().compareTo(allGetScore) == -1 || businessCategoryRule.getFourStarFloor().compareTo(allGetScore) == 0)
                        && (allGetScore.compareTo(businessCategoryRule.getFourStarUpper()) == -1 || allGetScore.compareTo(businessCategoryRule.getFourStarUpper()) == 0)) {
                    businessCategoryRuleHistory.setStartLevel(4);
                }
                //五星
                if ((businessCategoryRule.getFiveStarFloor().compareTo(allGetScore) == -1 || businessCategoryRule.getFiveStarFloor().compareTo(allGetScore) == 0)
                        && (allGetScore.compareTo(businessCategoryRule.getFiveStarUpper()) == -1 || allGetScore.compareTo(businessCategoryRule.getFiveStarUpper()) == 0)) {
                    businessCategoryRuleHistory.setStartLevel(5);
                }
                //生成证书
                FeignDrawImageDto feignDrawImageDto = new FeignDrawImageDto();
                if (businessCategoryTopicIsPassDto.getType() == 1) {
                    feignDrawImageDto.setBackgroundImageUrl("https://wxzz.obs.cn-south-1.myhuaweicloud.com:443/%E4%B8%AA%E4%BA%BA.1psd.jpg");
                    feignDrawImageDto.setNameText("获得人名称:" + jsonObject.getString("nickname"));
                }
                if (businessCategoryTopicIsPassDto.getType() == 0) {
                    feignDrawImageDto.setBackgroundImageUrl("https://wxzz.obs.cn-south-1.myhuaweicloud.com:443/%E5%B7%A5%E5%8E%82.1psd.jpg");
                    feignDrawImageDto.setNameText("获得工厂名称:" + enterpriseJson.getString("enterpriseName"));
                }
                feignDrawImageDto.setCreateTime("发证日期:" + LocalDate.now().toString());
                feignDrawImageDto.setStarText("星级:" + businessCategoryRuleHistory.getStartLevel());
                feignDrawImageDto.setEndTime("有效期至:" + LocalDate.now().plusYears(businessCategoryRule.getCredentialYear()).toString());
                feignDrawImageDto.setCredentialCode("证书编号:" + businessCategoryRuleHistory.getId());
                feignDrawImageDto.setItemText("项目名称:" + businessCategoryRule.getRuleName());
                feignDrawImageDto.setCredentialTextOne("技术要求:" + businessCategoryRule.getCredentialTextOne());
                feignDrawImageDto.setCredentialTextTwo("《" + businessCategoryRule.getCredentialTextTwo() + "》");
                feignDrawImageDto.setCredentialTextThree("上述项目符合:" + businessCategoryRule.getCredentialTextThree());
                if (StringUtils.isNotBlank(redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "commonUrl"))) {
                    //feignDrawImageDto.setCommonUrlOne(redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "commonUrl"));
                    feignDrawImageDto.setCommonUrlTwo(redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "commonUrl"));
                }
                String credentialUrl = obsApiFeign.getCredentialUrl(feignDrawImageDto);
                businessCategoryRuleHistory.setCredentialUrl(credentialUrl);
                businessCategoryRuleHistoryMapper.updateById(businessCategoryRuleHistory);
            }
            //工厂体检
            if (businessCategoryTopicIsPassDto.getType() == 0) {
                //查询本次的星级是否比企业的星级高
                FeignEnterpriseDto feignEnterpriseDto = enterpriseApiFeign.selectEnterpriseDtoById(jsonObject.getLong("enterpriseId"));
                if (feignEnterpriseDto != null && feignEnterpriseDto.getEnterpriseLevel() != null && feignEnterpriseDto.getEnterpriseLevel() < businessCategoryRuleHistory.getStartLevel()) {
                    //如果大于企业星级则修改
                    enterpriseApiFeign.updateEnterpriseStart(jsonObject.getLong("enterpriseId"), businessCategoryRuleHistory.getStartLevel());
                }
            }
            //星级认证
            if (businessCategoryTopicIsPassDto.getType() == 1) {
                //查询出最高的星级认证
                List<BusinessCategoryRuleHistory> businessCategoryRuleHistoryList = businessCategoryRuleHistoryMapper.selectList(new LambdaQueryWrapper<BusinessCategoryRuleHistory>()
                        .eq(BusinessCategoryRuleHistory::getType, 1)
                        .eq(BusinessCategoryRuleHistory::getBusinessCategoryRuleId, businessCategoryRule.getId())
                        .orderByDesc(BusinessCategoryRuleHistory::getStartLevel)
                        .last("limit 0,1"));
                //如果本次星级比之前的大 则记录
                List<WxUserBusinessCategoryGroup> wxUserBusinessCategoryGroupList = businessCategoryRuleMapper.selectBusinessCategoryRule4startId(jsonObject.getLong("id"), businessCategoryRule.getId());
                if (businessCategoryRuleHistoryList.size() == 0 || (businessCategoryRuleHistoryList.get(0).getStartLevel() != null && businessCategoryRuleHistoryList.get(0).getStartLevel() < businessCategoryRuleHistory.getStartLevel())) {
                    if (wxUserBusinessCategoryGroupList.size() > 0) {
                        //如果本次星级比之前的大 则记录
                        WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup = wxUserBusinessCategoryGroupList.get(0);
                        wxUserBusinessCategoryGroup.setTopStart(businessCategoryRuleHistory.getStartLevel());
                        wxUserBusinessCategoryGroupMapper.updateById(wxUserBusinessCategoryGroup);
                    }
                    //如果此次为5星判断班组所有人是否都达到了5星
                    if (wxUserBusinessCategoryGroupList.get(0) != null && businessCategoryRuleHistory.getStartLevel() != null && businessCategoryRuleHistory.getStartLevel() == 5) {
                        //查询该班组下的所有人
                        List<WxUserBusinessCategoryGroup> wxUserBusinessCategoryGroups = wxUserBusinessCategoryGroupMapper.selectList(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                                .eq(WxUserBusinessCategoryGroup::getCommonId, wxUserBusinessCategoryGroupList.get(0).getCommonId())
                                .eq(WxUserBusinessCategoryGroup::getType, 0)
                                .eq(WxUserBusinessCategoryGroup::getExamStatus, 0));
                        Boolean isAllFiveStar = Boolean.valueOf(Boolean.TRUE);
                        //判断是否都达到了5星
                        for (WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup : wxUserBusinessCategoryGroups) {
                            if (wxUserBusinessCategoryGroup.getTopStart() == null || wxUserBusinessCategoryGroup.getTopStart() != 5) {
                                isAllFiveStar = Boolean.FALSE;
                            }
                        }
                        //如果都达到了5星 则修改班组称号为五星班组
                        if (isAllFiveStar) {
                            BusinessCategoryRuleGroup businessCategoryRuleGroup = businessCategoryRuleGroupMapper.selectById(wxUserBusinessCategoryGroupList.get(0).getCommonId());
                            Optional.ofNullable(businessCategoryRuleGroup).orElseThrow(() -> new ServiceException("您所在班组不存在,请联系管理员"));
                            businessCategoryRuleGroup.setDesignation("五星班组");
                            businessCategoryRuleGroupMapper.updateById(businessCategoryRuleGroup);
                            //生成证书
                            FeignDrawImageDto feignDrawImageDto = new FeignDrawImageDto();
                            feignDrawImageDto.setBackgroundImageUrl("https://wxzz.obs.cn-south-1.myhuaweicloud.com:443/1623388825.jpg");
                            FeignWxUserDto feignWxUserDto = wxUserApiFeign.selectFeignWxUserDtoByWxUserId(jsonObject.getLong("id"));
                            feignDrawImageDto.setNameText("获得班组名称:" + feignWxUserDto.getOrganizationName());
                            feignDrawImageDto.setCreateTime("发证日期:" + LocalDate.now().toString());
                            feignDrawImageDto.setStarText("星级:" + businessCategoryRuleHistory.getStartLevel());
                            feignDrawImageDto.setEndTime("有效期至:" + LocalDate.now().plusYears(businessCategoryRule.getCredentialYear()).toString());
                            feignDrawImageDto.setCredentialCode("证书编号:" + businessCategoryRuleHistory.getId());
                            feignDrawImageDto.setItemText("项目名称:" + businessCategoryRule.getRuleName());
                            feignDrawImageDto.setCredentialTextOne("技术要求:" + businessCategoryRule.getCredentialTextOne());
                            feignDrawImageDto.setCredentialTextTwo("《" + businessCategoryRule.getCredentialTextTwo() + "》");
                            feignDrawImageDto.setCredentialTextThree("上述项目符合:" + businessCategoryRule.getCredentialTextThree());
                            if (StringUtils.isNotBlank(redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "commonUrl"))) {
                                //feignDrawImageDto.setCommonUrlOne(redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "commonUrl"));
                                feignDrawImageDto.setCommonUrlTwo(redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "commonUrl"));
                            }
                            String credentialUrl = obsApiFeign.getCredentialUrl(feignDrawImageDto);
                            businessCategoryRuleHistory.setCredentialUrl(credentialUrl);
                            businessCategoryRuleHistoryMapper.updateById(businessCategoryRuleHistory);
                        }
                    }
                }
                //统计班组排名
                if (wxUserBusinessCategoryGroupList.size() > 0) {
                    BusinessCategoryRuleGroupStatisticsData docentCurriculumStatisticsData = businessCategoryRuleGroupStatisticsDataMapper.selectOne(new LambdaQueryWrapper<BusinessCategoryRuleGroupStatisticsData>()
                            .eq(BusinessCategoryRuleGroupStatisticsData::getBusinessCategoryRuleGroupId, wxUserBusinessCategoryGroupList.get(0).getCommonId())
                            .eq(BusinessCategoryRuleGroupStatisticsData::getEnterpriseId, jsonObject.getLong("enterpriseId"))
                            .eq(BusinessCategoryRuleGroupStatisticsData::getSaveTime, LocalDate.now().toString())
                            .eq(BusinessCategoryRuleGroupStatisticsData::getEnterpriseOrganizationId, jsonObject.getLong("enterpriseOrganizationId")));
                    if (docentCurriculumStatisticsData == null) {
                        docentCurriculumStatisticsData = new BusinessCategoryRuleGroupStatisticsData();
                        docentCurriculumStatisticsData.setAllStarNum(businessCategoryRuleHistory.getStartLevel());
                        docentCurriculumStatisticsData.setBusinessCategoryRuleGroupId(wxUserBusinessCategoryGroupList.get(0).getCommonId());
                        docentCurriculumStatisticsData.setSaveTime(LocalDate.now().toString());
                        docentCurriculumStatisticsData.setTestNum(1);
                        docentCurriculumStatisticsData.setEnterpriseOrganizationId(jsonObject.getLong("enterpriseOrganizationId"));
                        docentCurriculumStatisticsData.setEnterpriseId(jsonObject.getLong("enterpriseId"));
                        businessCategoryRuleGroupStatisticsDataMapper.insert(docentCurriculumStatisticsData);
                    } else {
                        docentCurriculumStatisticsData.setAllStarNum(docentCurriculumStatisticsData.getAllStarNum() + businessCategoryRuleHistory.getStartLevel());
                        docentCurriculumStatisticsData.setTestNum(docentCurriculumStatisticsData.getTestNum() + 1);
                        businessCategoryRuleGroupStatisticsDataMapper.updateById(docentCurriculumStatisticsData);
                    }
                }
            }
            //题目选择数量
            businessCategoryRuleHistory.setAllScore(allGetScore);
            businessCategoryRuleHistoryMapper.updateById(businessCategoryRuleHistory);
            return new ReturnVO<>("测评结算成功", businessCategoryRuleHistory.getId());
        }
        //能力测评
        if (businessCategoryTopicIsPassDto.getType() == 2) {
            businessCategoryEvaluationHistory.setSuggest(suggest);
            //分组json
            if (businessCategoryTopicIsPassDto.getBusinessCategorys() != null) {
                businessCategoryEvaluationHistory.setBusinessCategorysJson(JSONObject.toJSONString(businessCategoryTopicIsPassDto.getBusinessCategorys()));
            }
            //设置测评辅助信息
            businessCategoryEvaluationHistory.setWxUserId(jsonObject.getLong("id"));
            businessCategoryEvaluationHistory.setEnterpriseId(jsonObject.getLong("enterpriseId"));
            businessCategoryEvaluationHistory.setBusinessCategoryEvaluationId(businessCategoryTopicIsPassDto.getCommonId());
            businessCategoryEvaluationHistory.setEnterpriseOrganizationId(jsonObject.getLong("enterpriseOrganizationId"));
            businessCategoryEvaluationHistory.setWxUserRealName(jsonObject.getString("nickname"));
            businessCategoryEvaluationHistory.setBusinessCategoryId(enterpriseJson.getLong("businessCategoryId"));
            businessCategoryEvaluationHistory.setEnterpriseName(enterpriseJson.getString("enterpriseName"));
            businessCategoryEvaluationHistory.setPhone(jsonObject.getString("phone"));
            businessCategoryEvaluationHistory.setIcon(jsonObject.getString("icon"));
            businessCategoryEvaluationHistory.setAnswerNum(chooseNum);
            BusinessCategoryEvaluation businessCategoryEvaluation = businessCategoryEvaluationMapper.selectById(businessCategoryTopicIsPassDto.getCommonId());
            if (businessCategoryEvaluation != null) {
                businessCategoryEvaluationHistory.setProjectName(businessCategoryEvaluation.getItemName());
            }
            //题目选择数量
            businessCategoryEvaluationHistory.setAllScore(allGetScore);
            businessCategoryEvaluationHistoryMapper.updateById(businessCategoryEvaluationHistory);
            return new ReturnVO<>("测评结算成功", businessCategoryEvaluationHistory.getId());
        }
        throw new ServiceException("结算失败");
    }

    @Autowired
    private BusinessCategoryRuleGroupStatisticsDataMapper businessCategoryRuleGroupStatisticsDataMapper;

    @Autowired
    private BusinessCategoryRuleGroupMapper businessCategoryRuleGroupMapper;

    @Autowired
    private TopicHistoryMapper topicHistoryMapper;

    @Override
    public ReturnVO<BusinessCategoryEvaluationHistory> selectBusinessCategoryEvaluationHistoryById(Long businessCategoryEvaluationHistoryId) {
        BusinessCategoryEvaluationHistory businessCategoryEvaluationHistory = businessCategoryEvaluationHistoryMapper.selectById(businessCategoryEvaluationHistoryId);
        Optional.ofNullable(businessCategoryEvaluationHistory).orElseThrow(() -> new ServiceException("该测评记录不存在"));
        //查询历史试题
        List<TopicHistory> topicHistories = topicHistoryMapper.selectList(new LambdaQueryWrapper<TopicHistory>()
                .eq(TopicHistory::getCommonId, businessCategoryEvaluationHistoryId)
                .eq(TopicHistory::getBusinessType, 2));
        for (TopicHistory topicHistory : topicHistories) {
            topicHistory.setAnswersArray(JSONObject.parseArray(topicHistory.getAnswers(), TopicAnswer.class));
        }
        businessCategoryEvaluationHistory.setTopicHistoryList(topicHistories);
        List<BusinessCategory> businessCategoryList = JSONObject.parseArray(businessCategoryEvaluationHistory.getBusinessCategorysJson(), BusinessCategory.class);
        List<String> businessNames = Lists.newArrayList();
        List<BigDecimal> businessCategoryPercentums = Lists.newArrayList();
        if (businessCategoryList != null) {
            for (BusinessCategory businessCategory : businessCategoryList) {
                //图表
                businessNames.add(businessCategory.getBusinessName());
                businessCategoryPercentums.add(businessCategory.getBusinessCategoryPercentum());
            }
        }
        businessCategoryEvaluationHistory.setBusinessCategorys(businessCategoryList);
        businessCategoryEvaluationHistory.setBusinessNames(businessNames);
        businessCategoryEvaluationHistory.setBusinessCategoryPercentums(businessCategoryPercentums);
        return new ReturnVO<>("测评结果查询成功", businessCategoryEvaluationHistory);
    }


    @Override
    public ReturnVO updateSuggest(UpdateSuggestDto updateSuggestDto) {
        //工厂体检/星级认证
        if (updateSuggestDto.getType() == 0 || updateSuggestDto.getType() == 1) {
            BusinessCategoryRuleHistory businessCategoryRuleHistory = businessCategoryRuleHistoryMapper.selectById(updateSuggestDto.getId());
            Optional.ofNullable(businessCategoryRuleHistory).orElseThrow(() -> new ServiceException("该工厂体检/星级认证记录不存在"));
            businessCategoryRuleHistory.setSuggest(updateSuggestDto.getSuggest());
            businessCategoryRuleHistoryMapper.updateById(businessCategoryRuleHistory);
        }
        //能力测评
        if (updateSuggestDto.getType() == 2) {
            BusinessCategoryEvaluationHistory businessCategoryEvaluationHistory = businessCategoryEvaluationHistoryMapper.selectById(updateSuggestDto.getId());
            Optional.ofNullable(businessCategoryEvaluationHistory).orElseThrow(() -> new ServiceException("该能力测评记录不存在"));
            businessCategoryEvaluationHistory.setSuggest(updateSuggestDto.getSuggest());
            businessCategoryEvaluationHistoryMapper.updateById(businessCategoryEvaluationHistory);
        }
        return new ReturnVO<>("建议修改成功", null);
    }

    @Override
    public ReturnVO<BusinessCategoryRuleHistory> selectBusinessCategoryRuleHistoryById(Long businessCategoryRuleHistoryId, Integer type) {
        BusinessCategoryRuleHistory businessCategoryRuleHistory = businessCategoryRuleHistoryMapper.selectById(businessCategoryRuleHistoryId);
        Optional.ofNullable(businessCategoryRuleHistory).orElseThrow(() -> new ServiceException("该检测已经不存在"));
        //查询历史试题
        List<TopicHistory> topicHistories = topicHistoryMapper.selectList(new LambdaQueryWrapper<TopicHistory>()
                .eq(TopicHistory::getCommonId, businessCategoryRuleHistoryId)
                .eq(TopicHistory::getBusinessType, type));
        for (TopicHistory topicHistory : topicHistories) {
            topicHistory.setAnswersArray(JSONObject.parseArray(topicHistory.getAnswers(), TopicAnswer.class));
        }
        businessCategoryRuleHistory.setTopicHistoryList(topicHistories);
        List<BusinessCategory> businessCategoryList = JSONObject.parseArray(businessCategoryRuleHistory.getBusinessCategorysJson(), BusinessCategory.class);
        List<String> businessNames = Lists.newArrayList();
        List<BigDecimal> businessCategoryPercentums = Lists.newArrayList();
        for (BusinessCategory businessCategory : businessCategoryList) {
            //图表
            businessNames.add(businessCategory.getBusinessName());
            businessCategoryPercentums.add(businessCategory.getBusinessCategoryPercentum());
        }
        businessCategoryRuleHistory.setBusinessCategorys(businessCategoryList);
        businessCategoryRuleHistory.setBusinessNames(businessNames);
        businessCategoryRuleHistory.setBusinessCategoryPercentums(businessCategoryPercentums);
        return new ReturnVO<>("测评结果查询成功", businessCategoryRuleHistory);
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @SneakyThrows
    @Transactional
    @Override
    public ReturnVO importTopic(String token, Long topicCategoryId, MultipartFile file) {
        //接口幂等处理
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(RedisConstants.TOPIC_IMPORT + token, token, 5, TimeUnit.SECONDS);
        if (!Boolean.TRUE.equals(aBoolean)) {
            throw new ServiceException("操作太频繁,请5秒后再试");
        }
        ExcelTopicUtils excelUtil = new ExcelTopicUtils();
        Workbook wb = excelUtil.getExcel(file);
        Sheet sheet = wb.getSheetAt(0);//读取sheet(从0计数)
        int rowNum = sheet.getLastRowNum();//读取行数(从0计数)
        int i = 0;
        try {
            Long topicId = null;//题目id
            Topic topic = null;//题目
            Long topicAnswerId = null;//答案id
            TopicAnswer topicAnswer = null;//答案选项
            for (; i <= rowNum; i++) {
                if (i < 1) {
                    //不读前一行
                    continue;
                }
                Row row = sheet.getRow(i);//获得行
                for (int j = 0; j < 7; j++) {
                    Cell cell = row.getCell(j);//获取单元格
                    //题目名称 如果题目名称为空 则让答案选项关联上一个题目数据
                    if (cell != null && StringUtils.isNotBlank(cell.toString())) {
                        //题目id
                        if (j == 0) {
                            topicId = Long.valueOf(cell.toString());
                        }
                        if (j == 1) {
                            topic = new Topic();
                            topic.setTopicCategoryId(topicCategoryId);
                            topic.setTopicName(cell.toString());
                        }
                        //设置限制个数
                        if (j == 2) {
                            topic.setChooseNum(excelUtil.format(cell.toString()));
                            if (topicId == null) {
                                topicMapper.insert(topic);
                            } else {
                                topic.setId(topicId);
                                topicMapper.updateById(topic);
                                topicId = null;//置空
                            }
                        }
                        //答案id
                        if (j == 3) {
                            topicAnswerId = Long.valueOf(cell.toString());
                        }
                        //选项
                        if (j == 4) {
                            topicAnswer = new TopicAnswer();
                            topicAnswer.setTopicId(topic.getId());
                            topicAnswer.setItem(String.valueOf(excelUtil.format(cell.toString())));
                        }
                        //答案
                        if (j == 5) {
                            topicAnswer.setAnswer(cell.toString());
                        }
                        //分数
                        if (j == 6) {
                            topicAnswer.setScore(new BigDecimal(cell.toString()));
                            if (topicAnswerId == null) {
                                topicAnswerMapper.insert(topicAnswer);
                            } else {
                                topicAnswer.setId(topicAnswerId);
                                topicAnswerMapper.updateById(topicAnswer);
                                topicAnswerId = null;//置空
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("导入测评题库出错[{}]", e.getMessage());
            throw new ServiceException("第" + (i + 1) + "行出错");
        }
        return new ReturnVO("题库导入成功", null);
    }

    @Override
    public void exportTopic(HttpServletResponse response, Long topicCategoryId) {
        TopicCategory topicCategory = topicCategoryMapper.selectById(topicCategoryId);
        Optional.ofNullable(topicCategory).orElseThrow(() -> new ServiceException("该分类不存在"));

        List<Topic> topicList = topicMapper.selectList(new LambdaQueryWrapper<Topic>()
                .eq(Topic::getTopicCategoryId, topicCategoryId));

        List<ExportTopicVo> exportTopicVos = Lists.newArrayList();
        for (Topic topic : topicList) {
            ExportTopicVo exportTopicVo = new ExportTopicVo();
            BeanUtils.copyProperties(topic, exportTopicVo);
            List<TopicAnswer> curriculumSectionTopicAnswers = topicAnswerMapper.selectList(new LambdaQueryWrapper<TopicAnswer>()
                    .eq(TopicAnswer::getTopicId, topic.getId()));
            List<ExportTopicAnswerVo> exportTopicAnswerVoList = Lists.newArrayList();
            for (TopicAnswer topicAnswer : curriculumSectionTopicAnswers) {
                ExportTopicAnswerVo exportTopicAnswerVo = new ExportTopicAnswerVo();
                BeanUtils.copyProperties(topicAnswer, exportTopicAnswerVo);
                exportTopicAnswerVoList.add(exportTopicAnswerVo);
            }
            exportTopicVo.setExportTopicAnswerVos(exportTopicAnswerVoList);
            exportTopicVos.add(exportTopicVo);
        }


        try {
            // 设置响应输出的头类型
            response.setHeader("content-Type", "application/vnd.ms-excel");
            // 下载文件的默认名称
            response.setHeader("Content-Disposition", "attachment;filename=testTopic.xls");

            ExportParams deptExportParams = new ExportParams();
            // 设置sheet得名称
            deptExportParams.setSheetName("测评试题");

            Map<String, Object> deptExportMap = new HashMap<>();
            // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
            deptExportMap.put("title", deptExportParams);
            // 模版导出对应得实体类型
            deptExportMap.put("entity", ExportTopicVo.class);
            // sheet中要填充得数据
            deptExportMap.put("data", exportTopicVos);

            List<Map<String, Object>> sheetsList = new ArrayList<>();
            sheetsList.add(deptExportMap);
            Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Autowired
    private BusinessCategoryEvaluationMapper businessCategoryEvaluationMapper;

    @Override
    public ReturnVO<JgPageVo<List<BusinessCategoryEvaluation>>> listBusinessCategoryEvaluation(Long wxUserId, WxBusinessCategoryEvaluationDto wxBusinessCategoryEvaluationDto) {
        ReturnVO<String> stringReturnVO = wxUserApiFeign.selectEnterpriseByWxUserId(wxUserId);
        List<BusinessCategoryEvaluation> businessCategoryEvaluations = null;
        if ("200".equals(stringReturnVO.getCode())) {
            JSONObject jsonObject = JSONObject.parseObject(stringReturnVO.getData());
            //取出企业的行业类目id
            Long businessCategoryId = jsonObject.getLong("businessCategoryId");
            PageHelper.startPage(wxBusinessCategoryEvaluationDto.getCurPage(), wxBusinessCategoryEvaluationDto.getMaxPage());
            QueryWrapper<BusinessCategoryEvaluation> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_time");
            queryWrapper.eq("business_category_id", businessCategoryId);
            if (StringUtils.isNotBlank(wxBusinessCategoryEvaluationDto.getItemName())) {
                queryWrapper.like("item_name", wxBusinessCategoryEvaluationDto.getItemName() + "%");
            }
            businessCategoryEvaluations = businessCategoryEvaluationMapper.selectList(queryWrapper);
            //需要移除的对象
            List<BusinessCategoryEvaluation> needRemove = Lists.newArrayList();
            for (BusinessCategoryEvaluation businessCategoryEvaluation : businessCategoryEvaluations) {
                //查询用户是否有权限
                WxUserBusinessCategoryGroup wxUserBusinessCategoryGroup = wxUserBusinessCategoryGroupMapper.selectOne(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                        .eq(WxUserBusinessCategoryGroup::getEnterpriseId, jsonObject.getLong("id"))
                        .eq(WxUserBusinessCategoryGroup::getType, 2)
                        .eq(WxUserBusinessCategoryGroup::getWxUserId, wxUserId)
                        .eq(WxUserBusinessCategoryGroup::getCommonId, businessCategoryEvaluation.getId())
                        .eq(WxUserBusinessCategoryGroup::getExamStatus, 0));
                //如果没有权限 则从列表移除
                if (wxUserBusinessCategoryGroup == null) {
                    needRemove.add(businessCategoryEvaluation);
                }
                Integer testNum = wxUserBusinessCategoryGroupMapper.selectCount(new LambdaQueryWrapper<WxUserBusinessCategoryGroup>()
                        .eq(WxUserBusinessCategoryGroup::getCommonId, businessCategoryEvaluation.getId())
                        .eq(WxUserBusinessCategoryGroup::getType, 2)
                        .eq(WxUserBusinessCategoryGroup::getEnterpriseId, jsonObject.getLong("id"))
                        .eq(WxUserBusinessCategoryGroup::getExamStatus, 0));
                businessCategoryEvaluation.setTestNum(testNum);
            }
            businessCategoryEvaluations.removeAll(needRemove);
        }
        return new ReturnVO<>("展示能力测评项目成功", new JgPageVo<>(new PageInfo(businessCategoryEvaluations)));
    }


}
